<template>
  <el-container style="height: 100vh">
    <Aside />
    <el-container>
      <el-main style="border-right: 1px solid transparent; border-image: linear-gradient(to bottom, #e0c3fc, #8ec5fc) 1 100%;">
        <h1 class="title" style="color: black">My Graphs</h1>
        <div>
          <br>
          <el-input
              v-model="searchQuery"
              placeholder="请输入搜索内容"
              style="margin-bottom: 20px; width: 300px;"
          >
            <template #prepend>
              <el-icon>
                <search />
              </el-icon>
            </template>
          </el-input>
          <el-space :fill=true wrap style="width: 80%">
            <el-card v-for="item in filteredItems" :key="item.Id" class="box-card">
              <template #header>
                <div class="card-header">
                  <h1 style="display: inline-block; font-size: 20px">表名:</h1>
                  <span style="display: inline-block; margin-left: 5%; font-size: 30px; font-weight: bold; color: darkcyan">{{item.Name}}</span>
                  <br>
                  <br>
                  <h3 style="display: inline-block;">创建时间: </h3>
                  <span style="display: inline-block; margin-left: 4%; font-size: 15px">{{item.CreateTime}}</span>
                  <br>
                  <hr>
                  <el-button class="button" @click="handleAnalyze(item.Id)">查看分析</el-button>
                  <el-button type="danger" @click="handleDelete(item.Id)">删除图谱</el-button>
                </div>
                <div :id="'chart-' + item.Id" class="chart-container" style="width: 100%; height: 400px;"></div>
              </template>
            </el-card>
          </el-space>
        </div>
      </el-main>
    </el-container>
  </el-container>
</template>

<script setup>
import Aside from '@/components/aside.vue';
import { ref, onMounted, nextTick, computed, watch } from 'vue';
import { deleteTable, getCommentByTableId, getTableByUserId } from "@/api/user.js";
import { ElMessage, ElMessageBox } from "element-plus";
import * as echarts from "echarts";

// 存储后端表格对象的数组
const items = ref([]);
const userId = ref('');

// 分析结论
const comment = ref('')

// 搜索框
const searchQuery = ref('');

// 查看当前表的分析
async function handleAnalyze(id) {
  try {
    // 使用 await 处理异步请求
    const response = await getCommentByTableId(id);
    console.log(response.code);

    if (response.code === 200) {
      // 获取评论内容
      comment.value = response.comment.Comment;
      console.log(comment.value);

      // 显示分析结论
      await ElMessageBox.alert(comment.value, '图谱分析结论', {
        confirmButtonText: '关闭',
      });
    } else {
      ElMessage({
        type: 'error',
        message: `错误: ${response.msg}`
      });
    }
  } catch (err) {
    console.log(err)
  }
}

// 搜索过滤
const filteredItems = computed(() => {
  if (!searchQuery.value) {
    return items.value;
  }
  const query = searchQuery.value.toLowerCase();
  return items.value.filter(item =>
      item.Name.toLowerCase().includes(query)
  );
});

// 监听 filteredItems，重新绘制图表
watch(filteredItems, (newItems) => {
  nextTick(() => {
    renderCharts(newItems);
  });
}, { deep: true });

// 删除图表
async function handleDelete(id) {
  try {
    const response = await deleteTable(id);
    if (response.code === 200) {
      ElMessage({
        type: 'success',
        message: '删除成功'
      });
      // 刷新表格列表
      await GetTableItems();
    } else {
      ElMessage({
        type: 'error',
        message: '删除失败'
      });
    }
  } catch (error) {
    ElMessage({
      type: 'error',
      message: '删除失败'
    });
    console.error("Failed to delete table:", error);
  }
}

// 获取后端的表格数据
async function GetTableItems() {
  const storedUser = localStorage.getItem('user');
  if (storedUser) {
    const parsedUser = JSON.parse(storedUser);
    if (parsedUser && parsedUser.id) {
      userId.value = parsedUser.id;

      // 查询表格数据
      try {
        const response = await getTableByUserId(userId.value);
        items.value = response.data;

        // 等待 DOM 完全更新后再渲染图谱
        await nextTick();
        renderCharts(response.data);
      } catch (error) {
        ElMessage({
          type: 'error',
          message: '查询表格数据失败'
        });
        console.error('获取表格数据时出错:', error);
      }
    }
  }
}

function renderCharts(data) {
  data.forEach(item => {
    // 解析图谱数据并去重
    const nodesMap = new Map();
    const links = [];
    const tableData = JSON.parse(item.TableData);

    tableData.forEach(data => {
      // 检查 node1, node2 和 relationship 是否为空
      const node1 = data.node1 ? data.node1.trim() : '';
      const node2 = data.node2 ? data.node2.trim() : '';
      const relationship = data.relationship ? data.relationship.trim() : '';

      if (node1 && node2 && relationship) {
        if (!nodesMap.has(node1)) {
          nodesMap.set(node1, { name: node1 });
        }
        if (!nodesMap.has(node2)) {
          nodesMap.set(node2, { name: node2 });
        }
        links.push({
          source: node1,
          target: node2,
          name: relationship,
        });
      }
    });

    // 获取对应的图谱容器
    const chartDom = document.getElementById('chart-' + item.Id);
    if (chartDom) {
      const myChart = echarts.init(chartDom, 'dark');

      const option = {
        title: {
          text: 'VC-kd',
          subtext: 'Node-Relationship-Node',
          top: 'bottom',
          left: 'right',
        },
        tooltip: {
          formatter: function (params) {
            if (params.dataType === 'edge') {
              return `Relationship: ${params.data.name}`;
            }
            return params.data.name;
          },
        },
        legend: [
          {
            data: [],
          },
        ],
        animationDuration: 1500,
        animationEasingUpdate: 'quinticInOut',
        series: [
          {
            name: 'Graph',
            type: 'graph',
            layout: 'force',
            data: Array.from(nodesMap.values()),
            links: links,
            roam: true,
            label: {
              position: 'right',
              formatter: '{b}',
            },
            lineStyle: {
              color: 'source',
              curveness: 0.3,
            },
            emphasis: {
              focus: 'adjacency',
              lineStyle: {
                width: 10,
              },
            },
            force: {
              repulsion: 1000,
            },
          },
        ],
      };

      myChart.setOption(option);
    } else {
      console.error(`未找到 ID 为 'chart-${item.Id}' 的元素。`);
    }
  });
}

onMounted(() => {
  GetTableItems();
});
</script>
<style>
@import url('https://fonts.googleapis.com/css2?family=Pacifico&display=swap');

html, body {
  height: 100%;
  margin: 0;
}

.chart-container {
  width: 100%;
  height: 400px; /* 你可以调整这个高度 */
  margin-top: 20px; /* 为了和其他内容分开一些 */
}

.main-content {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: flex-start;
  height: 100%;
  padding: 20px; /* 添加内边距以避免靠得太紧 */
}

.right-container {
  flex: 1;
  margin-left: 20px; /* 确保间距一致 */
}

.text-content {
  flex: 1;
  color: black;
  font-weight: 400;
  font-style: normal;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.content {
  font-size: 18px;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2), 0 6px 20px rgba(0, 0, 0, 0.19);
  margin: 20px;
  font-family: Arial, sans-serif;
  background: linear-gradient(to right, #8ec5fc, #e0c3fc);
}

.title {
  font-size: 50px;
  text-align: center;
  font-family: "Pacifico", cursive;
}

// 容器样式
.el-main {
  background-color: #E9EEF3;
  color: #333;
  text-align: center;
  line-height: 160px;
}

.el-header {
  background-color: #B3C0D1;
  color: #333;
  text-align: center;
  line-height: 60px;
  border-radius: 10px;
}

.el-container {
  background: linear-gradient(to right, #e0c3fc, #8ec5fc);
  height: 100%;
}
</style>
